import { createSlice } from "@reduxjs/toolkit";
import persistReducer from "redux-persist/es/persistReducer";
import sessionStorage from "redux-persist/es/storage/session";
import storage from "redux-persist/lib/storage";
const UserSlice = createSlice({
  name: "user",
  initialState: {
    user: {
      id: null,
      username: null,
      password: null,
      last_predict: "",
      last_result: "",
    },
  },
  reducers: {
    save_user_info: (state, actions) => {
      state.user = {
        last_predict: actions.payload.last_predict,
        last_result: actions.payload.last_result,
        ...actions.payload,
      };
    },
    reset_user_form: (state, actions) => {
      state.user = {
        id: 0,
        username: "",
        password: "",
        last_predict: "",
        last_result: "",
      };
    },
    get_user_object: (state) => {
      return state.user;
    },
  },
});

const userPersistConfig = {
  key: "user",
  storage: sessionStorage,
};

export const { save_user_info, reset_user_form, get_user_object } =
  UserSlice.actions;
export const userReducer = persistReducer(userPersistConfig, UserSlice.reducer);
